﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
//
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;


namespace AddResolution
{
    class Program
    {
        private static bool onlyVideo = false;
        private static int argsBase = 0;
        static void Main(string[] args)
        {
            if (args.Length > 1)
            {
                if ("-a" == args[0])
                {
                    argsBase = 1;
                    onlyVideo = true;
                }
            }
            if (argsBase == args.Length) { Usage(); return; }

            MI_connector mi = new MI_connector();
            List<string> files = new List<string>();
            //
            for (int i = argsBase; i < args.Length; i++)
            {
                string[] expandedFiles = expandWildcards(args[i]);
                foreach (string f in expandedFiles)
                {
                    files.Add(f);
                }
            }

            //
            /*
            for (int i = argsBase; i < args.Length; i++)
            {
                string[] expandedFiles = expandWildcards(args[i]);
                foreach (string f in expandedFiles)
                {
                }
            }
            */
            Parallel.ForEach<string>(files, currentFile =>
            {
                if (!File.Exists(currentFile))
                {
                    Console.WriteLine("[{0}]: Can't open!", currentFile);
                    goto _continue;
                }
                //
                string videoResolution, audioResolution;
                string resolution="";
                string newName="";
                try
                {
                    //
                    lock (mi)
                    {
                        if (!mi.getResolution(currentFile, out videoResolution, out audioResolution))
                        {
                            Console.WriteLine("[{0}]: Not a valid file!", currentFile);
                            goto _continue;
                        }
                    }
                    if (onlyVideo) audioResolution = "";
                    //
                    resolution = MkResolutionString(videoResolution, audioResolution);
                    //
                    //
                    VideoClipNameHelper.PathItems pi = new VideoClipNameHelper.PathItems(currentFile);
                    pi.FileName = VideoClipNameHelper.CleanFileName.CleanName(pi.FileName, false);
                    //Console.WriteLine("pi.FileName[{0}]", pi.FileName);
                    pi.FileName = GetNewFileName(pi.FileName, resolution);
                    newName = pi.Combine();
                    newName = newName.Replace("  ", " ");
                    //
                    //newName = VideoClipNameHelper.VCNC.GetNewFileName(currentFile, resolution);
                    //newName = Path.Combine(Path.GetDirectoryName(currentFile), VideoClipNameHelper.VCNC.CleanName(newName)) + Path.GetExtension(currentFile);
                    Console.WriteLine("[{0}]=>[{1}]", currentFile, newName);
                    //
                    Rename(currentFile, newName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\tERROR: {0},{1}", e.Message, e.StackTrace);
                }
                //
            _continue: ;
            });
            //
            return;
        }
        //
        static void Usage()
        {
            Console.WriteLine("Usage:");
            Console.WriteLine("{0} [-a] video_file_name ...", Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]));
            Console.WriteLine("-a - only video information");
            Console.WriteLine();
        }
        //
        static string[] expandWildcards(string pathName)
        {
            string[] fNames;
            //
            try
            {
                string dir = Path.GetDirectoryName(pathName);
                if ("" == dir) dir = ".";
                //
                fNames = Directory.GetFiles(dir, Path.GetFileName(pathName));
                if (0 == fNames.Length) return new string[] { pathName };
            }
            catch
            {
                return new string[] { pathName };
            }
            //
            return fNames;
        }
        //
        //private static readonly string resolutionPattern = @"\[(\d{3,}x\d{3,}.*?)\]";
        private static readonly string resolutionPattern = @"\[(.*?)\]";

        public static string RemoveOldResolution(string s)
        {
            //
            s = Regex.Replace(s, resolutionPattern, "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return s.TrimEnd();
        }



        //private static readonly string resolutionPattern = @"\d{3,}[xX]\d{3,}.*";
        //
        //private readonly string resolutionPatternOld = @"\((\d{3,}x\d{3,}.*?)\)";
        //private readonly string resolutionPatternNew = @"\[(\d{3,}x\d{3,}.*?)\]";
        //
        //
        public static string GetNewFileName(string fileNameWithoutExt, string resolution)
        {
            string newName = "";
            //string f = Path.GetFileNameWithoutExtension(fileName);
            string f = fileNameWithoutExt;
            //
            f = RemoveOldResolution(f);
            //f = CleanName(f);
            //
            //
            newName = Path.Combine(Path.GetDirectoryName(fileNameWithoutExt), f + resolution);
            //
            return newName;
        }


        public static string MkResolutionString(string videoResolution, string audioResolution)
        {
            string s = "";
            //
            videoResolution = videoResolution.ToLower();
            audioResolution = audioResolution.ToUpper();
            //
            if ("" == videoResolution && "" == audioResolution)
            {
                s = "";
            }
            else if ("" != videoResolution && "" == audioResolution)
            {
                s = videoResolution;
            }
            else if ("" == videoResolution && "" != audioResolution)
            {
                s = audioResolution;
            }
            else
            {
                s = videoResolution + "+" + audioResolution;
            }
            //
            //
            return "[" + s + "]";
        }

        public static bool Rename(string nameOld, string nameNew)
        {
            if (0 == String.Compare(nameOld, nameNew, false))//s╣ takie same
            {
                return true;
            }
            //
            if (0 == String.Compare(nameOld, nameNew, true))//rˇ┐nica tylko w case
            {
                //
                string tmpNewName = nameNew + "~";
                //
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName))
                {
                    throw new FileNotFoundException();// to nie jest dobre
                    //return false;
                }
                //
                File.Move(nameOld, tmpNewName);
                File.Move(tmpNewName, nameNew);
                //
                return true;
            }
            //
            File.Move(nameOld, nameNew);
            //
            return true;
        }

        //
    }//class
}//namespace
